
#include <cstdlib>
#include "freertos/FreeRTOS.h"
#include "esp_mac.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_bt.h"

#include "utils/BleSvr.h"
#include "device/RfidScanner.h"
#include "device/RgbLed.h"
#include "utils/CardUtils.h"

#define GPIO_LED    GPIO_NUM_44


volatile bool g_notify_flag;
uint16_t g_card_notify_handle;
uint16_t g_conn_handle;
uint8_t g_last_card[32];
uint8_t g_last_card_len = 0;
char g_device_name[32];
RfidScanner* g_pRfidScanner = nullptr;
CardUtils* g_pCardUtils = nullptr;

void notify_card(void* arg){
    while(true){
        if(g_pCardUtils && g_notify_flag){
            g_pCardUtils->notifyCard();
        }
        vTaskDelay(50 / portTICK_PERIOD_MS);
    }
}

extern "C" void app_main(void)
{
    esp_err_t ret;

    // Initialize NVS
    ret = nvs_flash_init();
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK( ret );

    uint8_t efuse_mac[6];
    ret = esp_read_mac(efuse_mac, ESP_MAC_BT);
    ESP_ERROR_CHECK(ret);
    sprintf(g_device_name, "YB-RF-%02X%02X", efuse_mac[4],
            efuse_mac[5]);

    g_pCardUtils = new CardUtils();
    xTaskCreate(notify_card, "notify_card", 1024 * 5, nullptr, 1, nullptr);

    //初始化LED灯
    // zero-initialize the config structure.
    gpio_config_t io_conf = {};
    // disable interrupt
    io_conf.intr_type = GPIO_INTR_DISABLE;
    // set as output mode
    io_conf.mode = GPIO_MODE_OUTPUT;
    // bit mask of the pins that you want to set,e.g.GPIO18/19
    io_conf.pin_bit_mask = (1ULL<< LED_POWER) | (1ULL<<LED_RUNNING);
    // disable pull-down mode
    io_conf.pull_down_en = GPIO_PULLDOWN_DISABLE;
    // disable pull-up mode
    io_conf.pull_up_en = GPIO_PULLUP_DISABLE;
    // configure GPIO with the given settings
    gpio_config(&io_conf);

    g_pRfidScanner = new RfidScanner();

    ESP_ERROR_CHECK(esp_nimble_hci_and_controller_init());

    nimble_port_init();
    /* Initialize the NimBLE host configuration */
    ble_hs_cfg.sync_cb = blehr_on_sync;
    ble_hs_cfg.reset_cb = blehr_on_reset;

    int rc = gatt_svr_init();
    assert(rc == 0);

    /* Set the default device name */
    rc = ble_svc_gap_device_name_set(g_device_name);
    assert(rc == 0);

    /* Start the task */
    nimble_port_freertos_init(blehr_host_task);

    RgbLed rgbLed;
    int led_on = 0;
    while(true){
        if(led_on){
            rgbLed.setColor(0,255,0);
        }else{
            rgbLed.setColor(0,0,0);
        }
        led_on = led_on == 0?1:0;
        vTaskDelay(1000 / portTICK_PERIOD_MS);
    }
}
